package cn.toutatis.sandbox.root.systemService.service.impl;


import cn.toutatis.common.config.PagingQuery;
import cn.toutatis.common.controllerDepand.GServiceImpl;
import cn.toutatis.sandbox.root.systemService.entity.SystemDictionary;
import cn.toutatis.sandbox.root.systemService.mapper.SystemDictionaryMapper;
import cn.toutatis.sandbox.root.systemService.service.SystemDictionaryService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * <p>
 * 静态字典 服务实现类
 * </p>
 *
 * @author Toutatis_Gc
 * @since 2020-07-09
 */
@Service
public class SystemDictionaryServiceImpl extends GServiceImpl<SystemDictionaryMapper, SystemDictionary> implements SystemDictionaryService {

    /**
     * 正常状态下间隔一段时间再更新，避免频繁连接数据库，默认为 UPDATE_INTERVAL 常量
     */
    private final static String NORMAL_STATUS = "SYSTEM_STATUS_0000";

    /**
     * 默认更新时长为5分钟
     */
    private final static long UPDATE_INTERVAL = 300;

    private Date updateTime = new Date();

    private String statusJson;

    @Override
    public String staticDic(String val) {
        if (NORMAL_STATUS.equals(val)){
            if (statusJson == null) { statusJson = toDicString(val); }
            long currentTime = System.currentTimeMillis() / 1000;
            long surplus = currentTime - (updateTime.getTime() / 1000);
            if (surplus >= UPDATE_INTERVAL){
                statusJson = toDicString(val);
                updateTime = new Date();
            }
            return statusJson;
        }
        return toDicString(val);
    }

    private String toDicString(String val){
        List<SystemDictionary> staticDic = baseMapper.staticDic(val);
        return toJSONString(staticDic);
    }

    @Override
    public List<SystemDictionary> getTree(Object id, PagingQuery pagingQuery) {
        return baseMapper.getTree(id,pagingQuery.getCurrentPage()-1,pagingQuery.getPageSize());
    }
}
